<?php
/**
 * 门店模型
 */

namespace app\badmin\model;


use app\badmin\model\CompanyShop as CompanyShopModel;
use app\common\lib\RedisKey;
use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use custom\Redis;
use custom\Token;
use think\Db;

class CompanyShop extends BaseModel {

    /**
     * 添加门店信息和门店账号
     * @param $params
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function add($params) {
        Db::startTrans();
        //公司 剩余可添加的最大经纪人人数
        $laveNum = CompanyAccount::getCompanyLaveNum($params['company_id']);
        if (!self::checkParams($params)) {
            return false;
        }
        if ($params['agent_num'] > $laveNum['lave_num']) {
            Err::add('可添加的最大经纪人人数超过了公司剩余可添加的经纪人人数', RespCode::PARAMS_ERR);
            return false;
        }
        if (!preg_match('/^1[3-9]\d{9}$/', $params['phone'])) {
            Err::add('门店电话号码不正确', RespCode::PARAMS_ERR);
            return false;
        }
        if ($params['pwd_again'] != $params['pwd']) {
            Err::add('两次密码输入不一致', RespCode::PARAMS_ERR);
            return false;
        }
        if (!preg_match('/^\w{6,15}$/', trim($params['pwd_again']))) {
            Err::add('密码：6-15位字母大小写数字下划线', RespCode::PARAMS_ERR);
            return false;
        }
        if (self::where('name', $params['name'])->where('company_id', $params['company_id'])->where('deleted', 0)->select()->toArray()) {
            Err::add('门店名称已被注册', RespCode::PARAMS_ERR);
            return false;
        }
        if (CompanyAccount::where('deleted', 0)->where('phone|account', $params['phone'])->select()->toArray()) {
            Err::add('该手机号已创建过账号', RespCode::PARAMS_ERR);
            return false;
        }
        if (count(explode('-', $params['city_code'])) != 2) {
            Err::add('默认城市参数错误', RespCode::PARAMS_ERR);
            return false;
        }
        //默认城市只能在公司拥有的城市当中选择
        $company_city_code = db("company")->where('id', $params['company_id'])->value('city_code');
        $company_city_code = explode(',', $company_city_code);
        if (!in_array($params['city_code'], $company_city_code)) {
            Err::add('默认城市参数错误', RespCode::PARAMS_ERR);
            return false;
        }
        //减少公司剩余可添加经纪人数
        if (!Company::lessAgentNum($params['agent_num'], $params['company_id'])) {
            Db::rollback();
            Err::add('操作异常请稍后尝试', RespCode::PARAMS_ERR);
            return false;
        };
        $data = [
            'company_id' => $params['company_id'],
            'name'       => $params['name'],
            'phone'      => $params['phone'],
            'address'    => $params['address'],
            'city_code'  => $params['city_code'],
            'agent_num'  => $params['agent_num'],
            'lave_num'   => $params['agent_num'],
            'lat'        => $params['lat'],
            'lng'        => $params['lng'],
            'itime'      => time(),
            'utime'      => time(),
        ];
        $newShopId = self::insertGetId($data);//添加门店信息
        if (!$newShopId) {
            Db::rollback();
            Err::add('操作异常请稍后尝试', RespCode::PARAMS_ERR);
            return false;
        }
        $companyAaccountData = [
            'company_id'      => $params['company_id'],
            'company_shop_id' => $newShopId,
            'phone'           => $params['phone'],
            'password'        => md5($params['pwd_again']),
            'account'         => $params['phone'],
            'deleted'         => 0,
            'itime'           => time(),
            'utime'           => time(),
        ];
        //添加门店账号
        if (!CompanyAccount::insert($companyAaccountData)) {
            Db::rollback();
            Err::add('操作异常请稍后尝试', RespCode::PARAMS_ERR);
            return false;
        }
        Db::commit();
        return true;
    }

    /**
     * 公司下面的门店列表
     * @param $params
     * @return array
     */
    public static function getList($params) {
        empty($params['page']) ? $page = 1 : $page = $params['page'];
        empty($params['long']) ? $long = 10 : $long = $params['long'];
        $column = ['ch.id', 'ch.name', 'ch.city_code', 'ch.address', 'ca.account', 'ch.agent_num', 'ch.lave_num'];
        $order = ['ch.id' => 'desc'];
        $map[] = ['ch.company_id', '=', $params['company_id']];
        $map[] = ['ch.deleted', '=', 0];
        if (!empty($params['ch_name'])) {
            $map[] = ['ch.name', 'like', '%' . trim($params['ch_name']) . '%'];
        }
        $data = self::list_query($map, $page, $long, $column, $order);
        foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['city_code'] = explode('-', $v['city_code'])[1];
        }
        return $data;
    }

    /**
     * 列表sql
     * @param $map
     * @param $page
     * @param $long
     * @param $column
     * @param $order
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function list_query($map, $page, $long, $column, $order) {
        $count = db("company_shop")
            ->alias('ch')
            ->join('company_account ca', 'ca.company_shop_id=ch.id')
            ->where($map)
            ->count();
        if ($count == 0) {
            $result = [
                'page'    => 1,
                'pageNum' => 1,
                'count'   => 0,
                'data'    => [],
            ];
            return $result;
        } else {
            $data = db("company_shop")
                ->alias('ch')
                ->join('company_account ca', 'ca.company_shop_id=ch.id')
                ->where($map)
                ->page($page, $long)
                ->field($column)
                ->order($order)
                ->select();
            $pageNum = ceil($count / $long);
            $result = [
                'page'    => $page,
                'pageNum' => $pageNum,
                'count'   => $count,
                'data'    => $data,
            ];
            return $result;
        }
    }

    /**
     * 验证参数
     * @param $params
     * @return bool
     */
    public static function checkParams(&$params) {
        if (preg_match("/^([\x{4e00}-\x{9fa5}]|\w){1,15}$/u", trim($params['name'])) == false) {
            Err::add('门店名字：15长度，数字、字母、汉字、下划线', RespCode::PARAMS_ERR);
            return false;
        }
        if (trim($params['name'] == '直属公司')) {
            Err::add('请重命名', RespCode::PARAMS_ERR);
            return false;
        }
        if (mb_strlen(trim($params['address']), 'utf-8') > 30) {
            Err::add('门店地址长度限制30', RespCode::PARAMS_ERR);
            return false;
        }
        return true;
    }

    /**
     * 编辑门店信息
     * @param $params
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function edit($params) {
        //公司 剩余可添加的最大经纪人人数
        $laveNum = CompanyAccount::getCompanyLaveNum($params['company_id']);
        $old = db("company_shop")
            ->where('id', $params['id'])
            ->find();
        if (empty($old) || $old['deleted'] == 1) {
            Err::add('数据不存在', RespCode::PARAMS_ERR);
            return false;
        }
        $old_password = db("company_account")->where('company_shop_id', $params['id'])->value('password');
        if (!self::checkParams($params)) {
            return false;
        }
        if ($params['agent_num'] < 1) {
            Err::add('最大经纪人数不能为0', RespCode::PARAMS_ERR);
            return false;
        }
        if (!empty($params['pwd']) || !empty($params['pwd_again'])) {//修改了密码
            if (empty($params['pwd'])) {
                Err::add('请输入密码', RespCode::PARAMS_ERR);
                return false;
            }
            if (empty($params['pwd_again'])) {
                Err::add('请确认密码', RespCode::PARAMS_ERR);
                return false;
            }
            if ($params['pwd'] != $params['pwd_again']) {
                Err::add('两次密码输入不一致', RespCode::PARAMS_ERR);
                return false;
            }
            if (!preg_match('/^\w{6,15}$/', trim($params['pwd_again']))) {
                Err::add('密码：6-15位字母大小写数字下划线', RespCode::PARAMS_ERR);
                return false;
            }
            $pwd = md5($params['pwd_again']);
        } else {
            $pwd = $old_password;
        }

        //默认城市只能在公司拥有的城市当中选择
        $company_city_code = db("company")->where('id', $params['company_id'])->value('city_code');
        $company_city_code = explode(',', $company_city_code);
        if (!in_array($params['city_code'], $company_city_code)) {
            Err::add('默认城市参数错误', RespCode::PARAMS_ERR);
            return false;
        }

        $hasName = db("company_shop")
            ->where("company_id", $params['company_id'])
            ->where("deleted", 0)
            ->where('name', $params['name'])
            ->select();
        if ($old['name'] != $params['name'] && $hasName) {
            Err::add('门店名称已被注册', RespCode::PARAMS_ERR);
            return false;
        }
        if ($laveNum['lave_num'] + $old['agent_num'] < $params['agent_num']) {
            Err::add('可添加的最大经纪人人数超过了公司剩余可添加的经纪人人数');
            return false;
        }
        Db::startTrans();
        if ($params['agent_num'] > $old['agent_num']) {//添加的最大人数比之前的大
            $a = $params['agent_num'] - $old['agent_num'];
            $b = $a + $old['lave_num'];
            if (!Company::lessAgentNum($a, $params['company_id'])) {
                Db::rollback();
                Err::add('操作异常请稍后尝试');
                return false;
            }
        } else {//添加的最大人数比之前的小
            $use_num = $old['agent_num'] - $old['lave_num'];//已使用经纪人数
            if ($use_num > $params['agent_num']) {
                Err::add('最大经纪人人数不能小于已添加经纪人数');
                return false;
            }
            $a = $old['agent_num'] - $params['agent_num'];
            if ($a > 0) {
                if (!Company::addAgentNum($a, $params['company_id'])) {
                    Db::rollback();
                    Err::add('操作异常请稍后尝试');
                    return false;
                }
            }
            $b = $params['agent_num'] - $use_num;
        }
        $data = [
            'name'      => $params['name'],
            'address'   => $params['address'],
            'city_code' => $params['city_code'],
            'agent_num' => $params['agent_num'],
            'lave_num'  => $b,
            'lng'       => $params['lng'],
            'lat'       => $params['lat'],
            'utime'     => time(),
        ];
        self::where('id', $params['id'])->update($data);
        if (!empty($params['pwd']) || !empty($params['pwd_again'])) {//修改了密码
            db('company_account')->where('company_shop_id', $params['id'])->update(['password' => $pwd]);
            $shop_id = db('company_account')->where('company_shop_id', $params['id'])->value('id');
            $redisModel = Redis::getInstance();
            $Token = new Token();
            $redisModel->hdel(RedisKey::BADMIN_TOKEN_HASH . '_' . $Token::BADMIN_TOKEN, $shop_id);
        }
        Db::commit();
        return true;
    }

    /**
     * 删除门店
     * @param $params
     * @return int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function del($params) {
        $exists = db("company_shop")->where('id', $params['id'])
            ->where('company_id', $params['company_id'])
            ->where('deleted', 0)
            ->find();
        if (empty($exists)) {
            Err::add('数据不存在', RespCode::PARAMS_ERR);
            return false;
        }
        CompanyAgent::hasAgent($params);
        $self = self::where('id', $params['id'])->field('agent_num,lave_num')->find();
        if ($self['agent_num'] != $self['lave_num']) {
            Err::add('门店有关联经纪人，不能删除', RespCode::PARAMS_ERR);
            return false;
        }
        Db::startTrans();
        //归还公司经纪人
        if (!Company::addAgentNum($self['agent_num'], $params['company_id'])) {
            Db::rollback();
            Err::add('操作异常请稍后尝试');
            return false;
        }
        //删除门店账号
        $re1 = CompanyAccount::del($params);
        if (!$re1) {
            Db::rollback();
            Err::add('操作异常请稍后尝试');
            return false;
        }
        //删除门店
        $re2 = self::where('id', $params['id'])
            ->where('company_id', $params['company_id'])
            ->update(['deleted' => 1]);
        if (!$re2) {
            Db::rollback();
            Err::add('操作异常请稍后尝试');
            return false;
        }
        Db::commit();
        return true;
    }

    /**
     * 筛选多条
     * @param $params
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getDatas($map, $column) {
        return db("company_shop")
            ->where($map)
            ->field($column)
            ->select();
    }

    /**
     * 经纪人数统计
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function agentNum($params) {
        $company_shop = db("company_shop")->where('id', $params['company_shop_id'])->field('agent_num,lave_num')->find();
        $useAgentNum = $company_shop['agent_num'] - $company_shop['lave_num'];//已使用的经纪人数
        $lave_num = $company_shop['lave_num']; //未使用经纪人数
        return [
            $lave_num,
            $useAgentNum,
        ];
    }

    /**
     * 获取单条
     * @param $map
     * @param $column
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOne($map, $column) {
        return db("company_shop")
            ->where($map)
            ->field($column)
            ->find();
    }

    /**
     * 减少剩余经纪人数
     * @param $company_shop_id
     * @throws \think\Exception
     */
    public static function lessAgent($company_shop_id, $num) {
        return self::where('id', $company_shop_id)
            ->setDec('lave_num', $num);
    }

    /**
     * 补回剩余经纪人数
     * @param $company_shop_id
     * @param $num
     * @throws \think\Exception
     */
    public static function addAgent($company_shop_id, $num) {
        return self::where('id', $company_shop_id)
            ->setInc('lave_num', $num);
    }

    /**
     * 获取详情
     * @param $params
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getInfo($params) {
        $info = CompanyShopModel::alias('cs')
            ->join('company_account ca', 'ca.company_shop_id = cs.id')
            ->where('cs.id', $params['id'])
            ->where('cs.deleted', 0)
            ->field('cs.id,cs.name,cs.phone,cs.address,cs.agent_num,cs.city_code,cs.lat,cs.lng,cs.lave_num')
            ->find();
        if (empty($info)) {
            Err::add('数据不存在', RespCode::PARAMS_ERR);
            return false;
        }
        return $info;
    }
}